package com.github.binarywang.demo.wx.mp.service.impl;

import com.github.binarywang.demo.wx.mp.service.MyOpenAiService;
import com.github.binarywang.demo.wx.mp.service.OpenAiServiceInterface;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import com.theokanning.openai.completion.chat.*;
import com.theokanning.openai.edit.EditChoice;
import com.theokanning.openai.edit.EditRequest;
import com.theokanning.openai.edit.EditResult;
import com.theokanning.openai.model.Model;
import com.theokanning.openai.service.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * @ClassName OpenAiService
 * @Description TODO
 * @Author tianwanming
 * @Date 2023/3/22 21:46
 * @Version 1.0
 */
@Service
public class OpenAiServiceImpl implements OpenAiServiceInterface {

    private OpenAiService openAiService = null;
    @Value("${openAi.OPENAI_TOKEN}")
    private String OPENAI_TOKEN = "";
    @Value("${openAi.BASE_URL}")
    private String BASE_URL = "";
//    @Resource
//    private Redis

    List<ChatMessage> messages = new ArrayList<>();

    @Override
    public String buildChat(String appid,String content) throws NoSuchFieldException, IllegalAccessException {

        if(Objects.isNull(openAiService)) {
            openAiService = new MyOpenAiService(OPENAI_TOKEN,BASE_URL);
        }
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), content);
        messages.add(chatMessage);

        ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
                .model("gpt-3.5-turbo")
                .messages(messages)
                .user(ChatMessageRole.USER.value())
                .n(3)
                .build();


        ChatCompletionResult chatCompletion = openAiService.createChatCompletion(completionRequest);
        List<ChatCompletionChoice> choiceList = chatCompletion.getChoices();
        if(CollectionUtils.isEmpty(choiceList)) {
            return null;
        }
        return choiceList.iterator().next().getMessage().getContent();
    }
}
